<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('上传照片')"/>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-boat-add" th:object="${boat}">
        <input name="id" th:field="*{id}" type="hidden">
        <div class="form-group">
            <label class="col-sm-3 control-label">名称：</label>
            <div class="col-sm-8">
                <input name="name" th:field="*{name}" class="form-control" type="text" disabled>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">编号：</label>
            <div class="col-sm-8">
                <input name="code" th:field="*{code}" class="form-control" type="text" disabled>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">照片：</label>
            <div class="col-sm-8">
                <input name="img" th:field="*{img}" class="form-control" type="file">
            </div>
        </div>

        <div class="form-group" style="text-align: center">
            <img id="boat-img" th:src="${'/boat/boat/img/' + boat.id}" alt="" style="max-width: 50%"
                 th:if="${boat.img != null}">
            <img id="preview-img" src="" alt="" style="max-width: 50%; display: none">
        </div>

    </form>
</div>
<th:block th:include="include :: footer"/>
<script th:inline="javascript">
    var prefix = ctx + "boat/boat"
    $("#form-boat-add").validate({
        focusCleanup: true
    });

    function submitHandler() {
        if ($.validate.form()) {
            uploadFile();
        }
    }

    function uploadFile() {
        var formData = new FormData();
        if ($('input[name=img]')[0].files[0] == null) {
            $.modal.alertWarning("请先选择文件路径");
            return false;
        }
        formData.append('id', $("input[name=id]").val());
        formData.append('file', $('input[name=img]')[0].files[0]);
        $.ajax({
            url: prefix + "/upload",
            type: 'post',
            cache: false,
            data: formData,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function (result) {
                $.operate.successCallback(result);
            }
        });
    }

    // 显示预览
    $('input[name=img]').on('change', function () {
        var file = this.files[0];
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#preview-img').attr('src', e.target.result);
            $('#preview-img').show();
            $('#boat-img').hide();
        }
        reader.readAsDataURL(file);
    });

</script>
</body>
</html>